<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>作业情况</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css"/>
</head>
<body class="pear-container">
<div class="layui-row layui-col-space10">
    <div class="layui-col-md12">
        <div class="layui-card">
            <form id="queryForm" class="layui-form" action="">
                <blockquote class="layui-elem-quote layui-quote-nm"><h3>发布作业</h3></blockquote>
                <div class="layui-form-item">
                    <label class="layui-form-label">选择课程</label>
                    <div class="layui-input-inline">
                        <select id="courseName" name="courseName" lay-verify="required" lay-search
                                lay-reqText="请选择目标课程" lay-filter="courseSelect">
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">选择班级</label>
                    <div class="layui-input-inline">
                        <select id="classes" name="classes" lay-verify="required" lay-search lay-reqText="请选择目标班级">
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">作业标题</label>
                    <div class="layui-input-inline">
                        <input id="taskName" type="text" name="taskName" lay-verify="required"
                               lay-reqText="请输入作业标题"
                               placeholder="请输入作业标题" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">截止日期</label>
                    <div class="layui-input-inline">
                        <input id="deadTime" type="text" name="deadTime" lay-verify="required"
                               lay-reqText="请选择截止日期"
                               placeholder="请选择截止日期" autocomplete="off" class="layui-input">
                    </div>
                    <button id="formVer" class="layui-btn" style="display: none"
                            lay-submit lay-filter="formVer">
                        发布作业
                    </button>
                </div>

            </form>
            <div class="layui-form-item">
                <label class="layui-form-label">作业附件</label>
                <div class="layui-inline">
                    <button class="layui-btn layui-btn-sm" id="uploadHFile">上传附件</button>
                    <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" id="emptyList">
                        清空上传列表
                    </button>
                </div>
            </div>
            <div class="layui-form-item">
                <table class="layui-table">
                    <colgroup>
                        <col>
                        <col width="150">
                        <col width="260">
                        <col width="150">
                    </colgroup>
                    <thead>
                    <tr>
                        <th>文件名</th>
                        <th>大小</th>
                        <th>上传进度</th>
                        <th>上传时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="fileList"></tbody>
                </table>
            </div>
            <hr style="border: solid 2px rgba(75,75,75,0.3);background-color: rgba(142,142,142,0.3)">
            <div class="layui-card-header"><h3>作业内容</h3></div>
            <div class="layui-card-body">
                <textarea name="taskClaim" id="taskClaim" cols="30" rows="10"></textarea>
                <div class="layui-btn-group" style="margin-top: 10px">
                    <button id="sendHomework" class="layui-btn" lay-filter="sendHomework"
                            lay-event="getContent">发布作业
                    </button>
                    <input type="hidden" id="sendHomeworkFile">
                </div>
            </div>
            </div>
    </div>
</div>
<script src="../../../component/layui/layui.js"></script>
<script src="../../../component/pear/pear.js"></script>
<script>
    layui.use(['tinymce', 'form', 'jquery', 'element', 'upload', 'laydate'], function () {
        let tinymce = layui.tinymce
        let form = layui.form;
        let $ = layui.jquery;
        let element = layui.element;
        let upload = layui.upload;
        let laydate = layui.laydate;
        let haveFiles = false;
        let files = {};
        let thisSubmit = false;


        form.on('select(courseSelect)', function (data) {
            //console.log(data.value);
            $('#classes').empty();
            $.ajax({
                url: '/relation/selectClassesByTeacherIdAndCourseName?courseName=' + data.value,
                dataType: 'json',
                type: 'post',
                success: function (res) {
                    if (res.code === 0) {
                        for (let i = 0; i < res.data.length; i++) {
                            $('#classes').append('<option value="' + res.data[i].classes + '">' +
                                res.data[i].classes + '</option>\n');
                        }
                        form.render('select'); //刷新select选择框渲染
                    } else {
                        layer.msg(res.msg, {icon: 5, anim: 6});
                    }
                },
                error: function (res) {
                    layer.open({
                        title: '提示'
                        , icon: 2
                        , content: '服务器处理异常，获取教师课程列表失败'
                    });

                }
            })
        })

        $('#sendHomework').click(function () {
            $('#formVer').click();
        });


        form.on('submit(formVer)', function (data) {
            if (thisSubmit){
                return false;
            }
            let json = $("form").serializeArray();
            if (haveFiles) {
                $('#sendHomeworkFile').click();
            } else {
                thisSubmit = true;
                $.ajax({
                    url: '/Task/getStudentsTaskByTaskId',
                    data: {
                        courseName:json[0].value,
                        classes:json[1].value,
                        taskName:json[2].value,
                        deadTime:json[3].value,
                        taskClaim:edit.getContent()

                    },
                    dataType: 'json',
                    type: 'post',
                    success: function (res) {
                        if (res.success) {
                            layer.msg(res.msg, {icon: 1, time: 1000}, function () {
                                parent.layer.close(parent.layer.getFrameIndex(window.name));//关闭当前页
                                parent.layui.table.reload("user-table", {
                                    data: res.data,
                                    page: {
                                        layout: ['count', 'prev', 'page', 'next', 'skip']
                                        , curr: parent.layui.jquery(".layui-laypage-em").next().html()
                                        , groups: 3
                                        , last: false
                                    }
                                });
                            });
                        } else {
                            layer.msg(res.msg, {icon: 5, anim: 6});
                        }
                    },
                    error: function (res) {
                        layer.open({
                            title: '提示'
                            , icon: 2
                            , content: '服务器处理异常，获取课程列表失败'
                        });

                    }
                })
            }
            return false;
        })


        function allAjax() {
            $.ajax({
                url: '/relation/selectCourseByTeacherId',
                dataType: 'json',
                type: 'post',
                success: function (res) {
                    if (res.success) {
                        for (let i = 0; i < res.data.length; i++) {
                            $('#courseName').append('<option value="' + res.data[i].courseName + '">' +
                                res.data[i].courseName + '</option>\n');
                        }
                        form.render('select'); //刷新select选择框渲染
                        $.ajax({
                            url: '/relation/selectClassesByTeacherIdAndCourseName?courseName=' + res.data[0].courseName,
                            dataType: 'json',
                            type: 'post',
                            success: function (res) {
                                if (res.code === 0) {
                                    for (let i = 0; i < res.data.length; i++) {
                                        $('#classes').append('<option value="' + res.data[i].classes + '">' +
                                            res.data[i].classes + '</option>\n');
                                    }
                                    form.render('select'); //刷新select选择框渲染
                                } else {
                                    layer.msg(res.msg, {icon: 5, anim: 6});
                                }
                            },
                            error: function (res) {
                                layer.open({
                                    title: '提示'
                                    , icon: 2
                                    , content: '服务器处理异常，获取教师课程列表失败'
                                });

                            }
                        })
                    } else {
                        layer.msg(res.msg, {icon: 5, anim: 6});
                    }
                },
                error: function (res) {
                    layer.open({
                        title: '提示'
                        , icon: 2
                        , content: '服务器处理异常，获取教师课程列表失败'
                    });

                }
            });

        }

        allAjax();
        //加载日期组件
        laydate.render({
            elem: '#deadTime',
            type: 'datetime',
            theme: 'molv',
            calendar: true
        });

        function clearFileList() {
            for (let x in uploadInst.config.files) {
                delete uploadInst.config.files[x];
            }
            $('#fileList').html('');
            haveFiles = false;
            //清空 input file 值，以免删除后出现同名文件不可选
            uploadInst.config.elem.next()[0].value = '';
        }

        //注册清空文件列表按钮事件
        $('#emptyList').click(function () {
            $('#fileList').html('');
            for (let x in uploadInst.config.files) {
                delete uploadInst.config.files[x];
            }
            haveFiles = false;
            //清空 input file 值，以免删除后出现同名文件不可选
            uploadInst.config.elem.next()[0].value = '';
            layer.msg('已清空上传列表', {icon: 1});
        });

        let edit = tinymce.render({
            elem: "#taskClaim",
            height: 400
            , plugins: ['table,link,quickbars']
            , images_upload_handler: function (blobInfo, succFun, failFun) {
                // 你的代码 ...
            },
            toolbar: [ //数组写法
                'newdocument undo redo| styleselect fontselect fontsizeselect| ' +
                'blockquote bullist numlist| bold italic underline strikethrough' +
                '| alignleft aligncenter alignright lineheight| superscript subscript'
            ]
        });

        //加载文件上传组件
        let uploadInst = upload.render({
            elem: '#uploadHFile' //绑定元素
            , url: '/Task/TeacherReleaseTask' //上传接口
            , elemList: $('#fileList') //列表元素对象
            , size: 1024 * 5
            , accept: 'file'
            , data: {
                courseName: function () {
                    // console.log('course的值如下');
                    let json = $("form").serializeArray();
                    console.log(json);
                    if (json.length === 0) {
                        return '';
                    } else {
                        return json[0].value;
                    }
                },
                classes: function () {
                    // console.log('course的值如下');
                    let json = $("form").serializeArray();
                    if (json.length === 0) {
                        return '';
                    } else {
                        return json[1].value;
                    }
                },
                taskName: function () {
                    // console.log('course的值如下');
                    let json = $("form").serializeArray();
                    if (json.length === 0) {
                        return '';
                    } else {
                        return json[2].value;
                    }
                },
                deadTime: function () {
                    // console.log('course的值如下');
                    let json = $("form").serializeArray();
                    if (json.length === 0) {
                        return '';
                    } else {
                        return json[3].value;
                    }
                },
                taskClaim: function () {
                    return edit.getContent();
                }
            }
            , number: 1
            , bindAction: '#sendHomeworkFile'
            , auto: false
            //, multiple: true
            , progress: function (n, elem, e, index) {
                //console.log(index);
                element.progress('progress-file-' + index, n + '%'); //执行进度条。n 即为返回的进度百分比
            }
            , done: function (res, index, upload) {
                let that = this;
                if (res.success) { //上传成功
                    let tr = that.elemList.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(4).html('<span class="layui-badge layui-bg-green">成功</span>'); //清空操作
                    delete this.files[index]; //删除文件队列已经上传成功的文件
                    haveFiles = false;
                    layer.msg(res.msg, {icon: 1, time: 1000}, function () {
                        parent.layer.close(parent.layer.getFrameIndex(window.name));//关闭当前页
                        parent.layui.table.reload("user-table", {
                            data: res.data,
                            page: {
                                layout: ['count', 'prev', 'page', 'next', 'skip']
                                , curr: parent.layui.jquery(".layui-laypage-em").next().html()
                                , groups: 3
                                , last: false
                            }
                        });
                    });
                    return;
                } else {
                    let tr = that.elemList.find('tr#upload-' + index)
                        , tds = tr.children();
                    this.error(index, upload);
                    layer.open({
                        title: '提示'
                        , icon: 2
                        , content: res.msg
                    });
                }

            }
            , allDone: function (obj) { //当文件全部被提交后，才触发
                console.log(obj)
                haveFiles = false;
            }
            , choose: function (obj) {
                clearFileList();
                let that = this;
                files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                haveFiles = true;
                //console.log(files);
                //console.log(uploadInst.config);
                //读取本地文件
                obj.preview(function (index, file, result) {
                    let date = new Date();
                    let tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td><div class="layui-progress" lay-filter="progress-file-' + index + '"><div class="layui-progress-bar" lay-percent=""></div></div></td>'
                        , '<td>' + date.toLocaleTimeString() + '</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs file-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger file-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.file-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.file-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        //清空 input file 值，以免删除后出现同名文件不可选
                        uploadInst.config.elem.next()[0].value = '';
                        haveFiles = false;
                    });
                    that.elemList.append(tr);
                    element.render('progress'); //渲染新加的进度条组件
                });
            }
            , error: function (index, upload) {
                let that = this;
                let tr = that.elemList.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(3).find('.file-reload').removeClass('layui-hide'); //显示重传
            }
        });
    });
</script>
</body>
</html>
